import { check } from 'meteor/check';
import { Channels, checkChannelId } from '/imports/models/Channels';
import { ChannelApps } from '/imports/models/ChannelApps';
import { ChannelMembers } from '/imports/models/ChannelMembers';
import { ChannelMessages } from '/imports/models/ChannelMessages';

Meteor.methods({
  // 创建频道
  createChannel(data) {
    if (checkChannelId(data.channelId)) {
      return Channels.insert(data, (error, result) => {
        if (error) {
          throw new Error(error);
        }
      });
    } else {
      throw new Meteor.Error('CHANNEL_ID_EXIST', '频道ID已被占用');
    }
  },
  // 更新频道信息
  updateChannel(id, data) {
    return Channels.update({_id: id}, {$set: data}, (error, result) => {
      if (error) {
        throw new Error(error);
      }
    });
  },
  getChannel(channelId) {
    check(channelId, String);
    return Channels.findOne({ channelId });
  },
  // 删除频道
  deleteChannel(id) {
    ChannelApps.remove({ channelId: id });

    ChannelMembers.remove({ channel_id: id });

    ChannelMessages.remove({ channelId: id });

    return Channels.remove({_id: id});
  }
});